<template>
  <!-- 搜索区域 -->
  <el-card shadow="never" class="henader-card">
    <div class="flx-row">
      <el-form :inline="true" :model="queryData" style="flex: 1">
        <!-- SN码搜索 -->
        <el-form-item label="SN码：" label-width="120px">
          <el-input
            v-model="queryData.snCode"
            placeholder="请输入SN码关键词"
            clearable
            class="input-width"
          />
        </el-form-item>

        <!-- 时间范围筛选（保留可选） -->
        <el-form-item label="时间范围：" label-width="100px">
          <el-date-picker
            v-model="queryData.date"
            type="datetimerange"
            :shortcuts="shortcuts"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>

        <!-- 分页大小选择 -->
        <el-form-item label="每页条数：" label-width="100px">
          <el-select
            v-model="queryData.size"
            @change="handleSizeChange"
            style="width: 180px"
          >
            <el-option label="10条/页" value="10" />
            <el-option label="20条/页" value="20" />
            <el-option label="50条/页" value="50" />
            <el-option label="100条/页" value="100" />
          </el-select>
        </el-form-item>
      </el-form>

      <div class="flex-right">
        <el-button type="primary" :icon="Search" @click="initData" class="ml20">
          搜索
        </el-button>
        <el-button
          type="primary"
          :icon="Download"
          @click="exportExcel"
          class="mr20"
        >
          导出数据
        </el-button>
      </div>
    </div>
  </el-card>

  <!-- 表格和分页部分 -->
  <el-card shadow="never">
    <el-table
      :data="tableData"
      :header-cell-style="{ backgroundColor: '#ecf5ff' }"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      empty-text="暂无数据"
    >
      <!-- 表格列配置（对应printdatainfo表字段） -->
      <el-table-column
        v-for="item in tableColumns"
        :key="item.props"
        :prop="item.props"
        :label="item.label"
        :align="item.align"
        :width="item.width"
        :fixed="item.fixed"
        show-overflow-tooltip
      >
        <!-- 时间格式化（创建时间/更新时间） -->
        <template 
          v-slot:default="scope" 
          v-if="item.props === 'createTime' || item.props === 'upDateTime'"
        >
          <span>{{ formatDate(scope.row[item.props]) }}</span>
        </template>

        <!-- 打印状态格式化（可选：根据实际状态值显示标签） -->
        <template v-slot:default="scope" v-if="item.props === 'printStatus'">
          <el-tag :type="getStatusType(scope.row.printStatus)">
            {{ scope.row.printStatus || '未打印' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件（复用） -->
    <el-pagination
      small
      background
      :page-size="queryData.size"
      layout="total, prev, pager, next, jumper"
      :total="total"
      class="mt-4"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script setup>
import * as XLSX from "xlsx";
import { Search, Download } from "@element-plus/icons-vue";
import { getPrintDataList } from "../../../api/modules/index.js"; // 新增的API接口
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { tableColumns } from "./options.js"; // 表格列配置

// 1. 查询参数
const queryData = ref({
  snCode: "", // SN码筛选
  page: 1,
  size: 10,
  date: [], // 时间范围
});

// 2. 表格数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// 3. 分页处理（复用）
const handleSizeChange = (val) => {
  queryData.value.size = val;
  queryData.value.page = 1;
  initData();
};

const handleCurrentChange = (val) => {
  queryData.value.page = val;
  initData();
};

// 4. 初始化数据
const initData = () => {
  loading.value = true;
  
  // 格式化日期为UTC（和后端时间匹配）
  const formatUTCDate = (date) => {
    if (!date) return "";
    const d = new Date(date);
    return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")} ${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")}:${String(d.getUTCSeconds()).padStart(2, "0")}`;
  };

  const { date, ...restParams } = queryData.value;
  const params = {
    ...restParams,
    SnCode: restParams.snCode, // 对应后端SNCode参数
    StartTime: formatUTCDate(date?.[0]),
    EndTime: formatUTCDate(date?.[1]),
  };

  // 调用条码打印列表接口
  getPrintDataList(params)
    .then((res) => {
      if (res.result === 1) {
        total.value = res.data.total;
        tableData.value = res.data.items || [];
      } else {
        ElMessage.error(res.message || "获取打印数据失败");
      }
    })
    .catch((err) => {
      ElMessage.error("网络错误，请重试");
      console.error(err);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 5. 工具函数
// 日期格式化（复用）
const formatDate = (isoString) => {
  if (!isoString) return "";
  const date = new Date(isoString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 打印状态标签类型（根据实际业务调整）
const getStatusType = (status) => {
  const statusMap = {
    '打印成功': 'success',
    '打印中': 'warning',
    '打印失败': 'danger',
    '未打印': 'info'
  };
  return statusMap[status] || 'info';
};

// 6. 导出Excel（复用逻辑，调整字段）
const exportExcel = () => {
  try {
    if (!tableData.value.length) {
      ElMessage.warning("当前页没有数据可导出");
      return;
    }

    const exportData = tableData.value.map((row) => ({
      "ID": row.id || "-",
      "SN码": row.snCode || "-",
      "排程号": row.scheduleCode || "-",
      "工单号": row.orderCode || "-",
      "创建时间": formatDate(row.createTime),
      "更新时间": formatDate(row.upDateTime),
      "打印状态": row.printStatus || "-"
    }));

    const data = XLSX.utils.json_to_sheet(exportData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, data, "条码打印记录");
    const fileName = `条码打印记录_${new Date()
      .toLocaleString()
      .replace(/[:/]/g, "-")}.xlsx`;
    XLSX.writeFile(wb, fileName);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 7. 日期快捷选项（复用）
const shortcuts = [
  {
    text: "今天",
    value: () => [
      new Date(new Date().setHours(0, 0, 0, 0)),
      new Date(new Date().setHours(23, 59, 59, 999)),
    ],
  },
  {
    text: "昨天",
    value: () => [
      new Date(new Date().getTime() - 24 * 60 * 60 * 1000),
      new Date(new Date().setHours(23, 59, 59, 999) - 24 * 60 * 60 * 1000),
    ],
  },
  {
    text: "近7天",
    value: () => [
      new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
      new Date(),
    ],
  },
];

// 8. 页面加载初始化
onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>
// 复用原有样式（和生产详情页面一致）
.henader-card {
  margin-bottom: 20px;
  padding: 15px 20px;
}

:deep(.el-form-item) {
  margin-right: 15px !important;
  margin-bottom: 10px !important;
  margin-top: 10px;
}

:deep(.el-form--inline .el-form-item) {
  display: inline-flex;
  align-items: center;
  margin-right: 15px !important;
  margin-bottom: 10px !important;
}

:deep(.el-form-item__label) {
  padding-right: 10px !important;
}

:deep(.el-form-item__content) {
  flex: 1;
}

.input-width {
  width: 180px;
}

:deep(.el-date-editor) {
  width: 300px;
}

.mt-4 {
  float: right;
  text-align: right;
  margin-top: 20px;
  margin-bottom: 20px;
}

:deep(.el-table .cell) {
  white-space: normal !important;
  word-break: break-all;
  line-height: 1.5;
}

.flx-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
}

.flex-right {
  display: flex;
  align-items: center;
  margin-left: auto;
}

.ml20 {
  margin-left: 20px;
}

.mr20 {
  margin-right: 20px;
}
</style>